import os
import mimetypes
from typing import List

class FileValidator:
    """文件验证类，用于检测和验证视频文件"""
    
    def __init__(self):
        # 支持的视频格式
        self.supported_video_extensions = {
            '.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', 
            '.webm', '.m4v', '.3gp', '.ogv', '.ts', '.mts'
        }
        
        # 支持的视频MIME类型
        self.supported_video_mimes = {
            'video/mp4', 'video/avi', 'video/quicktime', 'video/x-matroska',
            'video/x-ms-wmv', 'video/x-flv', 'video/webm', 'video/x-m4v',
            'video/3gpp', 'video/ogg', 'video/mp2t'
        }
    
    def is_video_file(self, file_path: str) -> bool:
        """
        检查文件是否为视频文件
        
        Args:
            file_path: 文件路径
            
        Returns:
            bool: 是否为视频文件
        """
        if not os.path.isfile(file_path):
            return False
        
        # 检查文件扩展名
        _, ext = os.path.splitext(file_path.lower())
        if ext in self.supported_video_extensions:
            return True
        
        # 检查MIME类型
        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type and mime_type.startswith('video/'):
            return True
        
        return False
    
    def scan_video_files(self, folder_path: str) -> List[str]:
        """
        扫描文件夹中的视频文件
        
        Args:
            folder_path: 文件夹路径
            
        Returns:
            List[str]: 视频文件路径列表
        """
        if not os.path.isdir(folder_path):
            raise ValueError(f"文件夹不存在: {folder_path}")
        
        video_files = []
        
        try:
            for root, dirs, files in os.walk(folder_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    if self.is_video_file(file_path):
                        video_files.append(file_path)
        except Exception as e:
            raise Exception(f"扫描文件夹时出错: {str(e)}")
        
        return sorted(video_files)
    
    def validate_folder_content(self, folder_path: str) -> dict:
        """
        验证文件夹内容，检查是否全是视频文件
        
        Args:
            folder_path: 文件夹路径
            
        Returns:
            dict: 验证结果
        """
        if not os.path.isdir(folder_path):
            return {
                'valid': False,
                'error': f"文件夹不存在: {folder_path}"
            }
        
        try:
            all_files = []
            video_files = []
            other_files = []
            
            for root, dirs, files in os.walk(folder_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    all_files.append(file_path)
                    
                    if self.is_video_file(file_path):
                        video_files.append(file_path)
                    else:
                        other_files.append(file_path)
            
            result = {
                'valid': len(other_files) == 0,
                'total_files': len(all_files),
                'video_files': len(video_files),
                'other_files': len(other_files),
                'video_file_paths': video_files,
                'other_file_paths': other_files
            }
            
            if len(other_files) > 0:
                result['error'] = f"发现 {len(other_files)} 个非视频文件"
            
            return result
            
        except Exception as e:
            return {
                'valid': False,
                'error': f"验证文件夹时出错: {str(e)}"
            }
    
    def get_file_info(self, file_path: str) -> dict:
        """
        获取视频文件信息
        
        Args:
            file_path: 文件路径
            
        Returns:
            dict: 文件信息
        """
        if not os.path.isfile(file_path):
            return {'error': '文件不存在'}
        
        try:
            stat = os.stat(file_path)
            _, ext = os.path.splitext(file_path)
            mime_type, _ = mimetypes.guess_type(file_path)
            
            return {
                'name': os.path.basename(file_path),
                'path': file_path,
                'size': stat.st_size,
                'extension': ext.lower(),
                'mime_type': mime_type,
                'is_video': self.is_video_file(file_path)
            }
        except Exception as e:
            return {'error': f"获取文件信息时出错: {str(e)}"} 